package yl.hs.bmipfull.service.salemanage.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yl.hs.bmipfull.controllers.salemanage.SaleOrderController;
import yl.hs.bmipfull.daos.salemanage.IContractControlInfoDao;
import yl.hs.bmipfull.daos.salemanage.ISaleContractDao;
import yl.hs.bmipfull.daos.salemanage.ISaleOrderDao;
import yl.hs.bmipfull.daos.salemanage.ISaleOrderProductDetailDao;
import yl.hs.bmipfull.pojo.production.BrickShipOrderDetailEntity;
import yl.hs.bmipfull.pojo.salemanage.ContractControlInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.LinkerInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.SaleOrderEntity;
import yl.hs.bmipfull.pojo.salemanage.SaleOrderProductDetailEntity;
import yl.hs.bmipfull.service.finance.IContractAccountService;
import yl.hs.bmipfull.service.salemanage.ISaleOrderService;
import yl.hs.bmipfull.utils.*;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.SaleOrderState;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.math.BigDecimal;
import java.util.*;

/*
 * SaleOrderServiceImpl
 * @category
 * @author 谢景广
 * @date 2021-06-02
 */
@Service
public class SaleOrderServiceImpl extends SaleBaseService implements ISaleOrderService {


    @Autowired
    ISaleOrderDao orderDao;
    @Autowired
    ISaleOrderProductDetailDao detailDao;
    @Autowired
    IContractAccountService contractAccountService;
    @Autowired
    IContractControlInfoDao contractControlInfoDao;
    @Override
    public PageResult<Object> queryContractOrders(PageQuery query, int rowNum, int page) throws Exception {
        query.checkSortSides(SaleOrderEntity.class);
        query.getQuery().put("querySkip", (page - 1) * rowNum);
        query.getQuery().put("pageSize", rowNum);
        PageResult<Object> result = new PageResult(rowNum);
        var snList = getConstructionContractSN();
        if (snList.size() > 0) {
            result.setRecords(orderDao.queryCountByCustom(query.getQuery(), snList));
            List<Object> list = new ArrayList<>();
            var ress = orderDao.queryDataByCustom(query.getQuery(), snList);
            for (SaleOrderEntity s : ress) {
                var map = s.toMap();
                var Detail =  detailDao.queryBySaleOrderSn(s.getSn());
                map.put("detail",Detail);
                list.add(map);
            }
            result.setData(list);
        } else {
            result.setRecords(0);
            result.setData(new ArrayList<>());
        }
        result.setPage(page);
        return result;
    }
    @Override
    public PageResult<Object> queryPage(PageQuery query, int rowNum, int page) {
        query.checkSortSides(SaleOrderEntity.class);
        query.getQuery().put("querySkip", (page - 1) * rowNum);
        query.getQuery().put("pageSize", rowNum);
        PageResult<Object> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(query.getFilters(), SaleOrderEntity.class);
        if(query.getQuery().get("haveAuthority")!=null && query.getQuery().get("haveAuthority").equals("0")){
            String[] str={};
            result.setRecords(orderDao.queryCountByQuery(query.getQuery(), str,filters));
            List<Object> list = new ArrayList<>();
            var ss = orderDao.queryListByQuery(query.getQuery(), str,filters);
            for (SaleOrderEntity s : ss) {
                var map = s.toMap();
                var Detail =  detailDao.queryBySaleOrderSn(s.getSn());
                map.put("detail",Detail);
                list.add(map);
            }
            result.setData(list);
        }else{
            result.setRecords(orderDao.queryCountByQuery(query.getQuery(), getTagSNs(),filters));
            List<Object> list = new ArrayList<>();
            var ss = orderDao.queryListByQuery(query.getQuery(), getTagSNs(),filters);
            for (SaleOrderEntity s : ss) {
                var map = s.toMap();
                var Detail =  detailDao.queryBySaleOrderSn(s.getSn());
                map.put("detail",Detail);
                list.add(map);
            }
            result.setData(list);
        }
        result.setPage(page);
        return result;
    }

    @Override
    public List<Object> queryList(PageQuery query) {
        query.checkSortSides(SaleOrderEntity.class);
        var filters = SearchFilterEngine.generateQueryList(query.getFilters(), SaleOrderEntity.class);
            var ss = orderDao.queryListByQuery(query.getQuery(), null,filters);
            List<Object> list = new ArrayList<>();
            for (SaleOrderEntity s : ss) {
                var map = s.toMap();
                var Detail =  detailDao.queryBySaleOrderSn(s.getSn());
                map.put("detail",Detail);
                list.add(map);
            }
            return list;
        }

    @Override
    public SaleOrderEntity findBySn(String sn) {
        return orderDao.findBySN(sn);
    }


    @Override
    public Integer saveSaleTask(Map<String, Object> data, String sn) throws Exception {
        var result = 0;
        if (Tl.isEmpty(sn)) {
            var entity = new SaleOrderEntity();
            Tl.getChangeLog(entity, data);
            entity.setSn(queryNewSN(entity.getClass()));
            entity.setPYFieldValue();
            entity.setAddTime(new Date());
            var user = HsApp.getCurrent();
            sendSysFeatherMessage("收到"+entity.getCustomerName()+"订单，请确认", CK.Production_Task_Feature,"新的销售订单");
            sendConstructMessage(user.getUserName()+"代表"+entity.getCustomerName() +"下单:",
                    entity.getContractSN(),user.getUserName()+"新增订单");
            saveGS(
                    entity.getSn(),
                    entity.getCustomerName(),
                    String.join(",",
                            entity.getCustomerName(),
                            entity.getCustomerName(),
                            entity.getRemark()
                    ),
                    entity,
                    HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                    null
            );
            List<Map<String,Object>> ss = (List<Map<String, Object>>) data.get("detail");
            List<SaleOrderProductDetailEntity> sale = new ArrayList<>();
            for (var i=0;i<ss.size();i++){
                var saledetail = new SaleOrderProductDetailEntity();
                try {
                    Tl.getChangeLog(saledetail,ss.get(i));
                    if(i==0){
                        saledetail.setSn(queryNewSN(SaleOrderProductDetailEntity.class));
                    }else{
                        var sns = queryNewSN(SaleOrderProductDetailEntity.class);
                        var entitysn = String.format("%04d",Integer.parseInt(sns.substring(sns.length() - 4)) + i);
                        saledetail.setSn(sns.substring(0,sns.length()-4)+entitysn);
                    }
                    saledetail.setSaleSn(entity.getSn());
                    sale.add(saledetail);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            };
            var la = false;
            for (SaleOrderProductDetailEntity item : sale) {
                la = checkControl(entity.getContractSN(),item.getProductSN(),item.getQuantity(),null,item.getProductCateSn());
            }
            if(la){
                return  -1;
            }
            result = orderDao.insertNew(entity);
            for (SaleOrderProductDetailEntity item : sale) {
                detailDao.insertNew(item);
            }
            writeLog(ActionType.CREATE, entity.getSn(), "创建销售订单", entity.toJson(), entity.getClass());
        } else {
            var entity = orderDao.findBySN(sn);
            if(entity.getState()>(short)2){
                return 0;
            }
            if (entity != null) {
                var backJson = entity.toJson();
                var changeLog = Tl.getChangeLog(entity, data);
                entity.setPYFieldValue();
                result = orderDao.update(entity);
                detailDao.deleteBySaleOrderSn(entity.getSn());
                List<Map<String,Object>> ss = (List<Map<String, Object>>) data.get("detail");
                ss.forEach(s->{
                    var saledetail = new SaleOrderProductDetailEntity();
                    try {
                        Tl.getChangeLog(saledetail,s);
                        saledetail.setSn(queryNewSN(SaleOrderProductDetailEntity.class));
                        saledetail.setSaleSn(entity.getSn());
                        detailDao.insertNew(saledetail);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                if (result > 0) {
                    saveGS(
                            entity.getSn(),
                            entity.getCustomerName(),
                            String.join(",",
                                    entity.getCustomerName(),
                                    entity.getCustomerName(),
                                    entity.getRemark()
                            ),
                            entity,
                            HsApp.getCurrent().getUserSN(),
                            null
                    );
                }
                writeLog(ActionType.UPDATE, entity.getSn(), changeLog, backJson, entity.getClass());
            }
        }
        return result;
    }

    @Override
    public Integer delete(String[] sn) {
        Integer result = orderDao.changeToState(sn, DataState.DELETED.code);
        writeLog(ActionType.DELETE, sn, SaleOrderEntity.class);
        deleteGs(sn);
        return result;
    }

    @Override
    public Integer changeToState(String[] sn, short state) {
        int result=orderDao.changeToState(sn, state);
        if (result > 0) {
            forWriteLog(sn,state);
        }
        return result;
    }

    @Override
    public Integer cancelOrder(String sn, short state) throws JsonProcessingException {
        var order =orderDao.findBySN(sn);
        if (order.getState()<=2) {
            var orderJson = order.toJson();
            order.setState(state);
            var user = HsApp.getCurrent();
            //writeLog(ActionType.DELETE, order.getSn(), "用户"+user.getUserName()+"在"+timeFormat.format(new Date())+"撤销了销售订单"+order.getSn(), orderJson, order.getClass());
            return orderDao.update(order);
        }
        return 0;
    }
    private boolean checkControl(String contractSn, String productSN, BigDecimal quantity, String productionTags, String productCateSn) throws Exception {
        var controlFlag = false;
        var ctlList= contractControlInfoDao.queryByContractSn(contractSn);
        if (ctlList.size() > 0) {

            var message = "";
            for (var control : ctlList) {
                var min = control.getStartTime();
                switch (control.getControlType()) {
                    case (short) 1://天数控制
                        Calendar dt = Calendar.getInstance();
                        dt.setTime(min);
                        dt.add(Calendar.DATE, (int) control.getDisabValue());
                        if ((new Date()).compareTo(dt.getTime()) > 0) {
                            controlFlag = true;
                            message = "已超过合同发货天数控制，禁止发货";
                        }
                        break;
                    case (short) 2:
                        if (!control.isControlWay()) {
                            /*var shipAmount = shipDAO.getControlShipAmountCount(control.getContractSN(), min);
                            shipAmount = shipAmount.add(quantity.multiply(shipDAO.getProductPrice(control.getContractSN(), productSN, new Date(), productionTags)));
                            if (shipAmount.compareTo(new BigDecimal(control.getDisabValue())) >= 0) {
                                controlFlag = true;
                                message = "已超过合同发货金额控制，禁止发货";
                            }*/
                        } else {
                            PageQuery model = new PageQuery();
                            Map<String, Object> map = new HashMap<>();
                            map.put("productCateSn", productCateSn);
                            map.put("sn", control.getContractSN());
                            model.setQuery(map);
                            var ss = contractAccountService.queryHfList(model, 1, 15);
                            if (ss != null && ss.getData() != null && ss.getData().size() > 0) {
                                var money = ss.getData().get(0).getContractBalance();
                                if (money.compareTo(new BigDecimal(control.getDisabValue())) < 0) {
                                    controlFlag = true;
                                    message = "已超过合同发货金额控制，禁止发货";
                                }
                            }
                        }
                        break;
                    case (short) 3:
                        /*var shipQuantity = shipDAO.getControlShipQuantityCount(control.getContractSN(), min);
                        shipQuantity = shipQuantity.add(quantity);
                        if (shipQuantity.compareTo(new BigDecimal(control.getDisabValue())) >= 0) {
                            controlFlag = true;
                            message = "已超过合同发货数量控制，禁止发货";
                        }*/
                        break;
                }
            }
        }
        return controlFlag;
    }
}
